<script setup lang="ts">
import { number } from 'echarts'
import { OrderState } from '@/services/constants'
import { orderStateList } from '@/services/constants'
import { putMemberOrderReceiptByIdAPI } from '@/services/order'
import { deleteMemberOrderAPI } from '@/services/order'
import { getMemberOrderAPI, putMemberOrderAPI } from '@/services/order'
import { getPayMockAPI, getPayWxPayMiniPayAPI } from '@/services/pay'
import type { OrderItem } from '@/types/order'
import type { OrderListParams } from '@/types/order'
import { onBackPress } from '@dcloudio/uni-app'
import { computed, onMounted, ref, watch, nextTick } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 获取弹窗组件
const updatePopup = ref<{
	open:(type?:UniHelper.UniPopupType) => void
	close:()=>void
}>()
// 定义 props
const props = defineProps<{
  orderState: number
}>()
console.log(props.orderState)

// 请求参数
const queryParams: Required<OrderListParams> = {
  page: 1,
  pageSize: 5,
  orderState: props.orderState,
}
watch(
  () => props.orderState,
  (newla, oldda) => {
    console.log(newla)
  },
)

// 获取订单列表
const orderList = ref<OrderItem[]>([])
// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)
const getMemberOrderData = async () => {
  // 如果数据出于加载中，退出函数
  if (isLoading.value) return
  // 退出分页判断
  if (isFinish.value === true) {
    return uni.showToast({ icon: 'none', title: '没有更多数据~' })
  }
  // 发送请求前，标记为加载中
  isLoading.value = true
  // 发送请求
  const res = await getMemberOrderAPI(queryParams)
  console.log(res)

  // 发送请求后，重置标记
  isLoading.value = false
  // 数组追加
  orderList.value.push(...res.data)
  // 分页条件
  if (queryParams.page < res.total) {
    // 页码累加
    queryParams.page++
  } else {
    // 分页已结束
    isFinish.value = true
  }
}

onMounted(() => {
  getMemberOrderData()
})

// 修改订单
const updateOrder = (row: any) => {
	formData.value.id = row.id
	formData.value.modify_price = row.modify_price
	formData.value.note_picture = row.note_picture
	formData.value.note = row.note || ""
	formData.value.status = row.status
	//可以成功打开了
	updatePopup.value?.open()
	console.log(row);
	
  
}
//订单修改数据
const formData = ref({
id:1,
modify_price:0,
note:"",
note_picture:"",
status:1
})
//清空修改订单数据
const init = ()=>{
	formData.value = {
	id:1,
	modify_price:0,
	note:"",
	note_picture:"",
	status:1
	}
}

//关闭修改订单页面
const cancel = ()=>{
	updatePopup.value?.close()
}
//点击确定 对表单进行校验 然后提交给后台接口
const submit = async()=>{
    console.log(formData.value);
    try {
        const res = await putMemberOrderAPI(formData.value);
        // 使用 setTimeout 延迟 500 毫秒（可根据实际情况调整）后再重新获取数据
        setTimeout(() => {
            getMemberOrderData();
        }, 500);
        //成功后关闭弹窗
        cancel();
        console.log(res);
    } catch (error) {
        console.error('提交订单修改时出错:', error);
    }
}
// 确认收货
const ConfirmReceipt = async (row: any) => {
  try {
    const res = await putMemberOrderAPI({
      id: row.id,
      modify_price: parseFloat(row.modify_price),
      note: row.note || '',
      note_picture: row.note_picture || '',
      status: 5,
    })
    if (res.code == '200') {
      uni.showToast({
        title: '修改成功',
        duration: 2000,
      })
      getMemberOrderData()
    } else {
      uni.showToast({
        title: '修改失败',
        duration: 2000,
      })
    }
  } catch (error) {
    uni.showToast({
      title: '修改失败',
      duration: 2000,
    })
    console.error(error)
  }
}

// 拒绝收货
const RefusalReceipt = async (row: any) => {
  try {
    const res = await putMemberOrderAPI({
      id: row.id,
      modify_price: parseFloat(row.modify_price),
      note: row.note || '',
      note_picture: row.note_picture || '',
      status: 4,
    })
    if (res.code == '200') {
      uni.showToast({
        title: '修改成功',
        duration: 2000,
      })
      getMemberOrderData()
    } else {
      uni.showToast({
        title: '修改失败',
        duration: 2000,
      })
    }
  } catch (error) {
    uni.showToast({
      title: '修改失败',
      duration: 2000,
    })
    console.error(error)
  }
}

// 删除订单
const onOrderDelete = (id: string) => {
  uni.showModal({
    content: '你确定要删除该订单？',
    confirmColor: '#27BA9B',
    success: async (res) => {
      if (res.confirm) {
        await deleteMemberOrderAPI({ ids: [id] })
        // 删除成功，界面中删除订单
        const index = orderList.value.findIndex((v) => v.id === id)
        orderList.value.splice(index, 1)
      }
    },
  })
}

// 是否分页结束
const isFinish = ref(false)
// 是否触发下拉刷新
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置数据
  queryParams.page = 1
  orderList.value = []
  isFinish.value = false
  // 加载数据
  await getMemberOrderData()
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <scroll-view
    enable-back-to-top
    scroll-y
    class="orders"
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="getMemberOrderData"
  >
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.ordertime }}</text>
        <!-- 订单状态文字 -->
        <!-- <text>{{ orderStateList[order.orderState].text }}</text> -->
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <!-- <text
          v-if="order.orderState >= OrderState.DaiPingJia"
          class="icon-delete"
          @tap="onOrderDelete(order.id)"
        ></text> -->
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->

      <!-- <navigator
        v-for="item in order.skus"
        :key="item.id"
        class="goods"
        :url="`/pagesOrder/detail/detail?id=${order.id}`"
        hover-class="none"
      >
        <view class="cover">
          <image class="image" mode="aspectFit" :src="item.image"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="type">{{ item.attrsText }}</view>
        </view>
      </navigator> -->

      <navigator class="goods" hover-class="none" :url="`/pagesOrder/detail/detail?id=${order.id}`">
        <view class="cover">
          <image class="image" mode="aspectFit" :src="order.pictureList[0].url"></image>
        </view>
        <view class="meta">
          <view class="name">名称：{{ order.meal_name }}</view>
          <view class="type">规格：{{ order.meal_spec }}</view>
          <text>备注：{{ order.note || '无' }}</text>
          <!-- <view>
            备注：<input
              class="inoutnote"
              type="text"
              v-model="order.note"
              placeholder="请输入备注信息"
              placeholder-class="input-placeholder"
              :disabled="props.orderState!=1"
            />
          </view> -->
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount">
          <text class="symbol">¥</text>{{ order.meal_count * order.meal_price }}</text
        >
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <!-- <template v-if="order.orderState === OrderState.DaiFuKuan">
          <view class="button primary" @tap="onOrderPay(order.id)">去支付</view>
        </template> -->
        <template v-if="props.orderState == 1">
          <view class="button primary" @tap="updateOrder(order)">修改订单</view>
          <view class="button primary" @tap="ConfirmReceipt(order)">确认收货</view>
          <view class="button secondary" @tap="RefusalReceipt(order)">拒绝收货</view>
        </template>
        <template v-if="props.orderState == 4">
          <view class="button primary" @tap="ConfirmReceipt(order)">确认收货</view>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ isFinish? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
  <!-- 弹窗组件 默认隐藏-->
  <uni-popup ref="updatePopup" type="bottom" background-color="#fff" class="updatePopup" >
	  <view class="orderUpdateForm">
	  		<uni-forms :modelValue="formData">
	  			<uni-forms-item label="价格" name="modify_price" >
<uni-easyinput type="number" v-model.number="formData.modify_price" placeholder="请输入价格" />
	  			</uni-forms-item>
				<uni-forms-item label="备注" name="note">
					<uni-easyinput type="text" v-model="formData.note" placeholder="请输入备注" />
				</uni-forms-item>
				<uni-forms-item label="图片" name="note_picture">
					<uni-easyinput type="text" v-model="formData.note_picture" placeholder="请修改照片" />
				</uni-forms-item>
	  		</uni-forms>
	  	  <view class="operate">
	  	  		<button size="mini" @tap="submit" >确定</button>
				<button size="mini" @tap="cancel" >取消</button>
	  	  </view>
	  	</view>
  </uni-popup>
</template>

<style lang="scss">
.inoutnote {
  transform: translateY(7px);
  display: inline-block;
  width: 260rpx;
  height: 50rpx;
  font-size: 14px;
  border-radius: 3px;
  padding-left: 3px;
  border: 1px rgb(160, 160, 160) solid;
}
// 订单列表
.orders {
 .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

 .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

   .date {
      color: #666;
      flex: 1;
    }

   .primary {
      color: #ff9240;
    }

   .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

 .goods {
    display: flex;
    margin-bottom: 20rpx;

   .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
     .image {
        width: 170rpx;
        height: 170rpx;
        overflow: hidden;
      }
    }

   .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

   .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

   .name {
      font-size: 26rpx;
      color: #444;
      margin-bottom: 10rpx;
    }

   .type {
      font-size: 26rpx;
      color: #444;
      margin-bottom: 10rpx;
    }

   .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

 .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

   .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

   .amount {
      color: #444;
      margin-left: 6rpx;
    }

   .symbol {
      font-size: 20rpx;
    }
  }

 .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

   .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

   .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

   .primary {
      color: #fff;
      background-color: #27ba9b;
      border-color: #27ba9b;
    }
  }

 .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
//弹窗组件样式
.updatePopup{
  .orderUpdateForm{
	  height: 480rpx;
	  padding: 20rpx;
	  .operate{
		  display: flex;
		  align-items: center;
		  justify-content: center;
	  }
  }
}
</style>